using System.ComponentModel;
using System.Security.Permissions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace CodeStory.WebControls
{
	[ToolboxItem(false)]
	[SupportsEventValidation]
	[AspNetHostingPermission(SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
	[AspNetHostingPermission(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
	internal class TreeGridChildTable : Table
	{
		// Fields
		private string _parentID;
		private bool _parentIDSet;
		private int _parentLevel;

		// Methods
		internal TreeGridChildTable() : this(1) {
		}

		internal TreeGridChildTable(int parentLevel) {
			this._parentLevel = parentLevel;
			this._parentIDSet = false;
		}

		internal TreeGridChildTable(string parentID) {
			this._parentID = parentID;
			this._parentIDSet = true;
		}

		protected override void AddAttributesToRender(HtmlTextWriter writer) {
			base.AddAttributesToRender(writer);
			string parentID = this._parentID;
			if (!this._parentIDSet) {
				parentID = this.GetParentID();
			}
			if (parentID != null) {
				writer.AddAttribute(HtmlTextWriterAttribute.Id, parentID);
			}
		}

		private string GetParentID() {
			if (this.ID == null) {
				Control parent = this;
				for (int i = 0; i < this._parentLevel; i++) {
					parent = parent.Parent;
					if (parent == null) {
						break;
					}
				}
				if ((parent != null) && !string.IsNullOrEmpty(parent.ID)) {
					return parent.ClientID;
				}
			}
			return null;
		}
	}
}